<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上载演示</title>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <!--引入Vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <!--引入Axios-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

</head>
<body>
<form id="demoForm" method="post"
      enctype="multipart/form-data"
      action="/upload/file" >
    <div>
        <label>上传文件
            <input id="imageFile" type="file" name="imageFile">
        </label>
    </div>
    <button type="submit">上传文件</button>
</form>
<img id="image" src=""  alt="">
</body>
<script>
$("#demoForm").submit(function () {
    //获得用户选中上传的文件
    let  files = document.getElementById("imageFile").files;
    //判断用户是否选中了文件
    if (files.length>0){
        //将用户选中的文件执行上传
        uploadFile(files[0]);
    }else {
        alert("请选择要上传的文件");
    }

    //阻止表单提交
    return false;
})
//上传文件的方法
    function uploadFile(file) {
        //创建表单
        let form = new FormData();
        form.append("imageFile",file);
        axios({
            url:"/upload/file",
            method:"post",
            data:form
        }).then(function (response) {
            console.log(response.data);
            //将上传的图片路径赋值给img标签的src属性
            $("#image").attr("src",response.data);
        })

    }
    </script>
</html>